package com.tea.service.impl;

import com.tea.service.FileStorageService;
import com.tea.utils.FileUpload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 本地文件存储服务实现
 * @author tea-shop
 */
@Slf4j
@Service
@ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "false", matchIfMissing = true)
public class LocalFileStorageServiceImpl implements FileStorageService {
    
    private static final String IMAGE_DIR = "/www/wwwroot/app/file/image";
    private static final String VIDEO_DIR = "/www/wwwroot/app/file/video";
    private static final String DOCUMENT_DIR = "/www/wwwroot/app/file/document";
    private static final String DOMAIN = "https://cclinkhub.cn:8080";
    
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        log.info("使用本地存储上传文件: {}", file.getOriginalFilename());
        return FileUpload.uploadFile(file);
    }
    
    @Override
    public String uploadFile(MultipartFile file, String directory) throws IOException {
        log.info("使用本地存储上传文件到目录 {}: {}", directory, file.getOriginalFilename());
        
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        String fileType = getFileType(file.getOriginalFilename());
        String targetDir = getTargetDirectory(fileType, directory);
        
        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "." + getFileExtension(file.getOriginalFilename());
        Path filePath = Paths.get(targetDir, fileName);
        
        // 确保目录存在
        Files.createDirectories(filePath.getParent());
        
        // 保存文件
        Files.write(filePath, file.getBytes());
        
        // 返回访问URL
        return buildFileUrl(fileType, fileName, directory);
    }
    
    @Override
    public String uploadBytes(byte[] bytes, String fileName, String contentType) {
        log.info("使用本地存储上传字节数组: {}", fileName);
        
        try {
            String fileType = getFileTypeFromContentType(contentType);
            String targetDir = getTargetDirectory(fileType, null);
            
            Path filePath = Paths.get(targetDir, fileName);
            
            // 确保目录存在
            Files.createDirectories(filePath.getParent());
            
            // 保存文件
            Files.write(filePath, bytes);
            
            return buildFileUrl(fileType, fileName, null);
        } catch (IOException e) {
            log.error("字节数组保存失败: {}", fileName, e);
            throw new RuntimeException("字节数组保存失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean deleteFile(String fileName) {
        log.info("使用本地存储删除文件: {}", fileName);
        
        try {
            // 尝试从不同目录删除文件
            String[] directories = {IMAGE_DIR, VIDEO_DIR, DOCUMENT_DIR};
            
            for (String dir : directories) {
                Path filePath = Paths.get(dir, fileName);
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                    log.info("文件删除成功: {}", filePath);
                    return true;
                }
            }
            
            log.warn("文件不存在: {}", fileName);
            return false;
        } catch (IOException e) {
            log.error("文件删除失败: {}", fileName, e);
            return false;
        }
    }
    
    @Override
    public boolean deleteFileByUrl(String fileUrl) {
        log.info("使用本地存储删除文件（URL）: {}", fileUrl);
        
        if (fileUrl == null || fileUrl.isEmpty()) {
            return false;
        }
        
        // 从URL中提取文件名
        String fileName = extractFileNameFromUrl(fileUrl);
        if (fileName == null) {
            log.warn("无法从URL中提取文件名: {}", fileUrl);
            return false;
        }
        
        return deleteFile(fileName);
    }
    
    @Override
    public boolean doesFileExist(String fileName) {
        String[] directories = {IMAGE_DIR, VIDEO_DIR, DOCUMENT_DIR};
        
        for (String dir : directories) {
            Path filePath = Paths.get(dir, fileName);
            if (Files.exists(filePath)) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public String getStorageType() {
        return "LOCAL";
    }
    
    /**
     * 获取文件类型
     */
    private String getFileType(String fileName) {
        String extension = getFileExtension(fileName).toLowerCase();
        
        if (extension.matches("(jpg|jpeg|png|gif|webp|svg|bmp|tiff|ico|avif)")) {
            return "image";
        } else if (extension.matches("(mp4|avi|mov|mkv|webm|wmv|flv|m4v|mpeg|3gp)")) {
            return "video";
        } else if (extension.matches("(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf)")) {
            return "document";
        }
        return "document"; // 默认为文档类型
    }
    
    /**
     * 根据Content-Type获取文件类型
     */
    private String getFileTypeFromContentType(String contentType) {
        if (contentType == null) {
            return "document";
        }
        
        if (contentType.startsWith("image/")) {
            return "image";
        } else if (contentType.startsWith("video/")) {
            return "video";
        }
        return "document";
    }
    
    /**
     * 获取目标目录
     */
    private String getTargetDirectory(String fileType, String customDirectory) {
        if (customDirectory != null && !customDirectory.isEmpty()) {
            return "/www/wwwroot/app/file/" + customDirectory.replaceAll("[^a-zA-Z0-9/]", "");
        }
        
        switch (fileType) {
            case "image":
                return IMAGE_DIR;
            case "video":
                return VIDEO_DIR;
            default:
                return DOCUMENT_DIR;
        }
    }
    
    /**
     * 构建文件访问URL
     */
    private String buildFileUrl(String fileType, String fileName, String customDirectory) {
        if (customDirectory != null && !customDirectory.isEmpty()) {
            return DOMAIN + "/" + customDirectory + "/" + fileName;
        }
        
        switch (fileType) {
            case "image":
                return DOMAIN + "/image/" + fileName;
            case "video":
                return DOMAIN + "/video/" + fileName;
            default:
                return DOMAIN + "/document/" + fileName;
        }
    }
    
    /**
     * 从URL中提取文件名
     */
    private String extractFileNameFromUrl(String fileUrl) {
        try {
            int lastSlashIndex = fileUrl.lastIndexOf("/");
            if (lastSlashIndex != -1 && lastSlashIndex < fileUrl.length() - 1) {
                return fileUrl.substring(lastSlashIndex + 1);
            }
        } catch (Exception e) {
            log.error("从URL提取文件名失败: {}", fileUrl, e);
        }
        return null;
    }
    
    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }
}